<?php

namespace App\Http\Controllers;

use App\Http\Requests\CampusCreate;
use App\Http\Requests\CampusUpdate;
use App\Models\Campus;
use Illuminate\Http\Request;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Redis;

class CampusController extends BaseController
{
    use ValidatesRequests;

    public function simpleList(Request $request)
    {
        $school_id =  $request->school_id;

        $where = [
            "school_id" => $school_id
        ];


        if(!Gate::check("checkSchoolAdmin", [$school_id]))
        {
            $where["user_id"] = Auth::id();
            $where["identity"] = "teacher";
            $res = Campus::whereHas('schoolUsers', function($su) use ($where){
                $su->where($where);
            })->get(["id", "school_id","campus_name"]);
        }else {
            $res = Campus::where($where)->get();
        }

        return resSucc($res, "校区列表");
    }

    public function list(Request $request)
    {
        $school_id =  $request->school_id;
        $limit =  $request->limit ?? 10;

        $where = [
            "school_id" => $school_id
        ];


        if(!Gate::check("checkSchoolAdmin", [$school_id]))
        {
            $where["user_id"] = Auth::id();
            $where["identity"] = "teacher";
            $res = Campus::whereHas('schoolUsers', function($su) use ($where){
                $su->where($where);
            })->paginate($limit);
        }else {
            $res = Campus::where($where)->paginate($limit);
        }

        return resSucc(formatPage($res), "校区列表");
    }

    // 编辑校区
    public function update(CampusUpdate $request){

        $campus = $request->validated();

        $campus_id = $request->campus_id;

        try{
            $res = Campus::where('id', $campus_id)->update($campus);
            return resSucc($res, "更新成功");
        } catch (\Exception $e) {
            return resFail($e, "更新失败");
        } catch (\Throwable $e) {
            return resFail($e, "更新失败");
        }
    }

    // 创建校区
    public function create(CampusCreate $request){

        $campus = $request->validated();

        $campus['school_id'] = $request->school_id;

        try{
            $res = Campus::create($campus);
            return resSucc($res, "创建成功");
        } catch (\Exception $e) {
            return resFail($e, "创建失败");
        } catch (\Throwable $e) {
            return resFail($e, "创建失败");
        }

    }
}
